<?PHP
class mysql2json{

 function getJSON($resultSet,$affectedRecords){
 $numberRows=0;
 $arrfieldName=array();
 $i=0;
 $json="";
	//print("Test");
 	while ($i < mysql_num_fields($resultSet))  {
 		$meta = mysql_fetch_field($resultSet, $i);
		if (!$meta) {
		}else{
		$arrfieldName[$i]=$meta->name;
		}
		$i++;
 	}


	 $i=0;
	  $json="\n { label: 'title', identifier: 'storyid', items: [\n";
	  $catFolder = "";
	  $dataArray = array();
	  
	while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
	 $dataArray[] = $row;
	}

	for($r=0;$r < count($dataArray);$r++){
	
	
	//echo "<B>storyid:</B> " . $dataArray[$r][0] . " - <B>title:</B> " . $dataArray[$r][1] . " - <B>category:</B> " . $dataArray[$r][2] . " - <B>category title:</B> ". $dataArray[$r][3] . "<P>";
		
		//for categories with no conten str_replace("'", "\'", $dataArray[$r][3]);
		if($dataArray[$r][0] == ""){
			$json .= "{storyid:\"CAT".$r."\",title:'".str_replace("'", "\'", $dataArray[$r][3])."', type:'category'";
			if($r == count($dataArray)){
				$json .= "}";
			}else{
				$json .= "},";
			}
		}else{
		
		//create a category folder
			if($catFolder == ""){
				$json .= "{storyid:\"CAT".$r."\",title:'".str_replace("'", "\'", $dataArray[$r][3])."', type:'category',children: [ ";
				$catFolder = $dataArray[$r][2];
			}
		

		//create body
			while(isset($dataArray[$r][2]) && $catFolder == $dataArray[$r][2]){
				$json.="{";
				$json.="\"".$arrfieldName[0]."\" :	\"".$dataArray[$r][0]."\",";
				$json.="\"".$arrfieldName[1]."\" :	\"".$dataArray[$r][1]."\",";
				$json.="\"".$arrfieldName[2]."\" :	\"".$dataArray[$r][2]."\",";
				$json.="\"".$arrfieldName[3]."\" :	\"".$dataArray[$r][3]."\"";
				if(isset($dataArray[$r+1][2]) && $dataArray[$r+1][2] == $catFolder){
					$json.="},";
				}else{
					$json.="}";
				}
				
				$r++;
			}
		
	
			
		//close json row
			$catFolder = "";
			if($r == count($dataArray)){
				$json .= "]}";
			}else{
				$json .= "]},";
				$r--;
			}
			
		}//end else for if($dataArray[$r][0] == ""){
			
	}//end for loop
	
	
	$json.="]\n}";
	
	return $json;
	
 }
}
?>

